package com.example.a10.controller;

import com.example.a10.util.AddressConstants;
import com.example.a10.entity.Document;
import com.example.a10.util.DocumentUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/Train")
public class TrainController {

    @ApiOperation("上传测试文件")
    @PostMapping("/Upload")
    public List<Document> TestUpload(MultipartFile file) throws IOException {
        //判断多个文件上传个数是否为0
        if(file!=null){
            //获取文件名
            String name = file.getOriginalFilename();
            file.transferTo(new File(AddressConstants.Train+name));
        }
        return selectTrainlist();
    }

    @ApiOperation("返回训练文件名称，删除模型")
    @DeleteMapping("/delete")
    public String deleteTrain(@RequestBody Document document){
        if(document!=null){
            String name = document.getName();
            File file = new File(AddressConstants.Train+name);
            file.delete();
            return "success";
        }else {
            return "failed";
        }
    }

    @ApiOperation("返回所有训练文件的所有名称")
    @GetMapping("/Trainlist")
    @ResponseBody
    public List<Document> selectTrainlist(){
        File file = new File(AddressConstants.Train);
        String[] Trainlist = file.list();
        List<Document> documents = new ArrayList<>();
        for (String train:Trainlist){
            Document document = new Document();
            document.setName(train);
            String filesize = DocumentUtil.getFilesize(AddressConstants.Train + train);
            document.setSize(filesize);
            documents.add(document);
        }
        return documents;
    }
}
